"""
API客户端模块
负责与远程API进行通信
"""

import time
import logging
from typing import Dict, Any, Optional, Callable
import requests

logger = logging.getLogger(__name__)

def retry_operation(func: Callable, max_retries: int = 3, delay: int = 1):
    """
    重试操作的装饰器
    
    Args:
        func: 要重试的函数
        max_retries: 最大重试次数
        delay: 重试延迟（秒）
        
    Returns:
        装饰后的函数
    """
    def wrapper(*args, **kwargs):
        retries = 0
        while retries < max_retries:
            try:
                return func(*args, **kwargs)
            except Exception as e:
                retries += 1
                if retries >= max_retries:
                    raise e
                logger.warning(f"操作失败，正在重试 ({retries}/{max_retries}): {e}")
                time.sleep(delay * retries)  # 指数退避
    return wrapper

class ApiClient:
    """API客户端类，用于与远程API交互"""
    
    def __init__(self, base_url: str, timeout: int = 30, api_key: Optional[str] = None):
        """
        初始化API客户端
        
        Args:
            base_url: API基础URL
            timeout: 请求超时时间（秒）
            api_key: API密钥（可选）
        """
        self.base_url = base_url
        self.timeout = timeout
        self.api_key = api_key
        self.session = requests.Session()
        
        if api_key:
            self.session.headers.update({"Authorization": f"Bearer {api_key}"})
    
    def get(self, endpoint: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
        """
        发送GET请求
        
        Args:
            endpoint: API端点
            params: 查询参数
            
        Returns:
            API响应
        """
        url = f"{self.base_url}/{endpoint}"
        response = self.session.get(url, params=params, timeout=self.timeout)
        response.raise_for_status()
        return response.json()
    
    def post(self, endpoint: str, data: Dict[str, Any]) -> Dict[str, Any]:
        """
        发送POST请求
        
        Args:
            endpoint: API端点
            data: 请求数据
            
        Returns:
            API响应
        """
        url = f"{self.base_url}/{endpoint}"
        response = self.session.post(url, json=data, timeout=self.timeout)
        response.raise_for_status()
        return response.json()
    
    def put(self, endpoint: str, data: Dict[str, Any]) -> Dict[str, Any]:
        """
        发送PUT请求
        
        Args:
            endpoint: API端点
            data: 请求数据
            
        Returns:
            API响应
        """
        url = f"{self.base_url}/{endpoint}"
        response = self.session.put(url, json=data, timeout=self.timeout)
        response.raise_for_status()
        return response.json()
    
    def delete(self, endpoint: str) -> Dict[str, Any]:
        """
        发送DELETE请求
        
        Args:
            endpoint: API端点
            
        Returns:
            API响应
        """
        url = f"{self.base_url}/{endpoint}"
        response = self.session.delete(url, timeout=self.timeout)
        response.raise_for_status()
        return response.json()
    
    @retry_operation
    def fetch_with_retry(self, endpoint: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
        """
        带重试的GET请求
        
        Args:
            endpoint: API端点
            params: 查询参数
            
        Returns:
            API响应
        """
        return self.get(endpoint, params)